package com.cq.androidtools.datastore

import androidx.datastore.core.CorruptionException
import androidx.datastore.core.Serializer
import androidx.datastore.preferences.protobuf.InvalidProtocolBufferException
import com.cq.androidtools.protobuf.UserPrefs.UserPreferences
import java.io.InputStream
import java.io.OutputStream

/**
 * 作者: CQ
 * 日期: 2021-03-31
 * 说明:
 */
object UserPreferencesSerializer : Serializer<UserPreferences> {
    override val defaultValue: UserPreferences = UserPreferences.getDefaultInstance()
    override fun readFrom(input: InputStream): UserPreferences {
        try {
            // 是编译器自动生成的，用于读取并解析 input 的消息
            return UserPreferences.parseFrom(input)
        } catch (exception: InvalidProtocolBufferException) {
            throw CorruptionException("Cannot read proto.", exception)
        }
    }

    override fun writeTo(t: UserPreferences, output: OutputStream) = t.writeTo(output)// t.writeTo(output) 是编译器自动生成的，用于写入序列化消息
}